package com.example.springblog.controller;

import com.example.springblog.enums.ResultCodeEnum;
import com.example.springblog.model.Result;
import com.example.springblog.model.UserInfo;
import com.example.springblog.service.UserService;
import com.example.springblog.utils.JwtUtils;
import com.example.springblog.utils.SecurityUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String userName , String password){
        if(!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)){
            return Result.fail("用户名或密码为空" , ResultCodeEnum.PARAM_INVILD.getCode());
        }
        UserInfo userInfo = userService.login(userName);
        if(userInfo == null || userInfo.getId() == null){
            return Result.fail("用户不存在" , ResultCodeEnum.PARAM_INVILD.getCode());
        }

        if(!SecurityUtils.verify(password , userInfo.getPassword())){
            return Result.fail("用户密码错误" , ResultCodeEnum.PARAM_INVILD.getCode());
        }
        Map<String,Object> cliams = new HashMap<>();
        cliams.put("id", userInfo.getId());
        cliams.put("name", userInfo.getUserName());

        String jwt = JwtUtils.genJwt(cliams);
        return Result.success(jwt);
    }

    @RequestMapping("/getUserInfo")
    public UserInfo getUserInfo(HttpServletRequest request){
        String userToken = request.getHeader("user_token_header");
        Integer userId = JwtUtils.getUserIdFromToken(userToken);
        UserInfo userInfo = userService.selectUserInfoById(userId);
        return userInfo;
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        Assert.notNull(blogId , "blogId不能为空");
        UserInfo userInfo = userService.selectAuthorInfoById(blogId);
        return userInfo;
    }
}







